﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace PServiceBus.Core.Runtime {
    public class JsonSettings {
        const string DEFAULT_FILENAME = "psb.json";
        private Dictionary<string, object> _settings = new Dictionary<string, object>();
        private string _fileName;

        public JsonSettings(string fileName) {
            _fileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, fileName);
            LoadSettings();
        }

        private static JsonSettings _default;
        public static JsonSettings Default {
            get { return _default ?? (_default = new JsonSettings(DEFAULT_FILENAME)); }
        }

        private void LoadSettings() {
            if (!File.Exists(_fileName)) return;
            _settings = ServiceStack.Text.JsonSerializer.DeserializeFromString<Dictionary<string, object>>(
                File.ReadAllText(_fileName));
        }

        public T GetOrAdd<T>(string key, T value) {
            return GetOrAdd<T>(key, () => value);
        }

        public T GetOrAdd<T>(string key, Func<T> func) {
            object obj;
            if (_settings.TryGetValue(key, out obj))
                return ServiceStack.Text.JsonSerializer.DeserializeFromString<T>(obj.ToString());
            return (T)(_settings[key] = func());
        }

        public T Get<T>(string key) {
            object obj;
            if (_settings.TryGetValue(key, out obj))
                return ServiceStack.Text.JsonSerializer.DeserializeFromString<T>(obj.ToString());
            return default(T);
        }

        public void AddAndSave<T>(string key, T value) {
            this[key] = value;
            Save();
        }

        public void RemoveAndSave(string key) {
            if (_settings.ContainsKey(key))
                _settings.Remove(key);
            Save();
        }

        public object this[string key] {
            get {
                return _settings[key];
            }
            set {
                _settings[key] = value;
            }
        }

        public void Save() {
            File.WriteAllText(_fileName, ServiceStack.Text.JsonSerializer.SerializeToString(_settings));
        }
    }
}
